from psychopy import visual, core, event

# 创建一个窗口
win = visual.Window(size=[800, 600], color=(1, 1, 1), units='pix')

# 创建一个文本刺激
message = visual.TextStim(win, text="Hello, PsychoPy!", color=(-1, -1, -1))

# 定义关闭窗口的函数
def close_window():
    if win.winHandle is None:
        print("Window has been closed by the user.")
        core.quit()

# 注册全局按键事件
event.globalKeys.add(key='escape', func=core.quit, name='quit')

# 主循环以保持窗口打开并检查事件
while win.winHandle is not None:
    # 绘制文本刺激
    message.draw()

    # 刷新窗口以显示内容
    win.flip()

    # 检查窗口是否已关闭
    close_window()

    # 小延迟以防止高CPU使用率
    core.wait(0.01)

# 关闭窗口
win.close()

# 退出PsychoPy
core.quit()
